#!/usr/bin/env python
import os
import tarfile
import docker
import commands
#from utils.log import log

import datetime
import time
#from utils.get_date import datelist
from get_date import datelist

def execute(code):
    write_data(code)
    create_file("test.py", "output.py")
    list_date = []
    list_data = []
    list_data_tmp = []
    a = run_in_docker()
    #log.info("In execute, the result of run_in_docker:%s" % a)
    str_line = a.split('[')[1]
    str_line = str_line.split(']')[0]
    #log.info("In execute: the result of run_in_docker:%s" % str_line)
    list_data_tmp = str_line.split(',')

    for i in range(len(list_data_tmp)-1):
        list_data.append(float(list_data_tmp[i]))
    length = len(list_data)
    
    #To get list_date 
    end = datetime.datetime.now().strftime('%Y/%m/%d')
    #log.info("curent date: %s" % end)

    #To get the arguments for datelist()
    this_y = int(end.split("/")[0])
    this_m = int(end.split("/")[1])
    this_d = int(end.split("/")[2])
    start = datetime.datetime.now() + datetime.timedelta(days=-1*length)
    start = start.strftime('%Y/%m/%d')
    start_y = int(start.split("/")[0])
    start_m = int(start.split("/")[1])
    start_d = int(start.split("/")[2])
    #To run datelist()
    list_date = datelist((start_y, start_m, start_d), (this_y, this_m, this_d))
    #log.info("In execute(), list_date: %s" %list_date)
    return list_date, list_data

def write_data(data):
    output_file = open('output.py', 'wb')
    output_file.write(data)
    output_file.close()

def create_file(file1, file2):
    file_origin = open(file1, "r")
    content = file_origin.read()
    content_add = ""
    pos = content.find("#insert above")

    #if the code is not written in the file 'file2', then pass.
    if os.path.getsize(file2) == 0:
        content = content[:pos] + "    pass\n" + content[pos:]
    else:
        file_add = open(file2, "r")
        while 1:
            line = file_add.readline()
            if not line:
                break
            new_line = line.rstrip() + '\n'
            content_add = content_add + new_line
        content = content[:pos] + content_add + content[pos:]
        file_add.close()

    file_origin = open("./new_sim.py", "w")
    file_origin.write(content)
    file_origin.close()

def run_in_docker():
    tar = tarfile.open("dockertar.tar", "w")
    tar.add("simulation0.py")
    #tar.add("./new_sim.py")
    tar.add("fetchdata.py")
    tar.add("train_svc.py")
    tar.add("tranpoint.py")
    tar.add("tool.py")
    tar.add("show.py")
    tar.add("data")
    tar.close()
    #print "tar is created."
    #log.info("tar is created.")
    data = open("dockertar.tar").read()

    status, container_id = commands.getstatusoutput("docker run -d -i -t zwc/ubuntu17.10:beta /bin/bash")
    #log.info("In docker: %s %s" % (status, container_id))
    client = docker.from_env()
    con = client.containers.get(container_id)
    con.put_archive('/root', data)
    #ret = con.exec_run("python /root/new_sim.py")
    ret = con.exec_run("python /root/simulation0.py")
    print "In docker, result: %s" % ret
    con.kill()
    
    return ret

if __name__ == "__main__":
    print run_in_docker()
	
